package com.xxl.job.admin.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.thread.JobScheduleHelper;
import com.xxl.job.admin.core.thread.JobTriggerPoolHelper;
import com.xxl.job.admin.core.trigger.TriggerTypeEnum;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.dao.XxlJobUserDao;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * index controller
 *
 * @author xuxueli 2015-12-19 16:13:16
 */
@Controller
@RequestMapping("/xxl-job-admin/jobinfo")
public class JobInfoController {
    private static Logger logger = LoggerFactory.getLogger(JobInfoController.class);

    @Resource
    private XxlJobService xxlJobService;
    @Resource
    private XxlJobInfoDao xxlJobInfoDao;
    @Resource
    private XxlJobUserDao xxlJobUserDao;


    @PreAuthorize("@ss.hasPermi('xxl:job:info:query')")
    @RequestMapping("/pageList")
    @ResponseBody
    public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,
                                        @RequestParam(required = false, defaultValue = "10") int length,
                                        int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
        XxlJobUser loginUser = xxlJobUserDao.loadByUserName(SecurityUtils.getUsername());
        return xxlJobService.pageList(loginUser, start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
    }

    @PreAuthorize("@ss.hasPermi('xxl:job:info:add')")
    @RequestMapping("/add")
    @ResponseBody
    public ReturnT<String> add(@RequestBody XxlJobInfo jobInfo) {
        return xxlJobService.add(jobInfo);
    }

    @PreAuthorize("@ss.hasPermi('xxl:job:info:update')")
    @RequestMapping("/update")
    @ResponseBody
    public ReturnT<String> update(@RequestBody XxlJobInfo jobInfo) {
        return xxlJobService.update(jobInfo);
    }

    @PreAuthorize("@ss.hasPermi('xxl:job:info:remove')")
    @RequestMapping("/remove")
    @ResponseBody
    public ReturnT<String> remove(HttpServletRequest request, int id) {
        XxlJobInfo jobInfo = xxlJobInfoDao.loadById(id);
        return xxlJobService.remove(id);
    }

    @PreAuthorize("@ss.hasPermi('xxl:job:info:stop')")
    @RequestMapping("/stop")
    @ResponseBody
    public ReturnT<String> pause(HttpServletRequest request, int id) {
        XxlJobInfo jobInfo = xxlJobInfoDao.loadById(id);
        return xxlJobService.stop(id);
    }

    @PreAuthorize("@ss.hasPermi('xxl:job:info:start')")
    @RequestMapping("/start")
    @ResponseBody
    public ReturnT<String> start(HttpServletRequest request, int id) {
        XxlJobInfo jobInfo = xxlJobInfoDao.loadById(id);
        return xxlJobService.start(id);
    }

    /**
     * 执行一次
     * @param id
     * @param executorParam
     * @param addressList
     * @return
     */
    @PreAuthorize("@ss.hasPermi('xxl:job:info:trigger')")
    @RequestMapping("/trigger")
    @ResponseBody
    public ReturnT<String> triggerJob(int id, String executorParam, String addressList) {
        // force cover job param
        if (executorParam == null) {
            executorParam = "";
        }
        JobTriggerPoolHelper.trigger(id, TriggerTypeEnum.MANUAL, -1, null, executorParam, addressList);
        return ReturnT.SUCCESS;
    }

    @PreAuthorize("@ss.hasPermi('xxl:job:info:query')")
    @RequestMapping("/nextTriggerTime")
    @ResponseBody
    public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {

        XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
        paramXxlJobInfo.setScheduleType(scheduleType);
        paramXxlJobInfo.setScheduleConf(scheduleConf);

        List<String> result = new ArrayList<>();
        try {
            Date lastTime = new Date();
            for (int i = 0; i < 5; i++) {
                lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
                if (lastTime != null) {
                    result.add(DateUtil.formatDateTime(lastTime));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")) + e.getMessage());
        }
        return new ReturnT<List<String>>(result);

    }
}
